<?php

namespace App\Console\Commands;

use App\BookApply;
use App\Document;
use App\PatentApply;
use App\PatentAssess;
use App\PlantVariety;
use App\Transverse;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;

class MoveLocalFileCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:move:file {action}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $action = $this->argument('action');
        if ($action == 'move') {
            //php artisan command:move:file move
            $this->move();
        } elseif ($action == 'download') {
            //php artisan command:move:file download
            $this->download();
        }
    }

    protected function download()
    {
        $count = 0;
        PatentApply::query()->orderBy('id')
            ->chunk(100, function ($list) use (&$count) {
                $list->map(function (PatentApply $model) use (&$count) {
                    foreach (['file', 'cert', 'retrieval_report'] as $field) {
                        if ($path = $model->$field) {
                            $storage = Storage::disk('ali_oss');
                            if ($storage->exists($path)) {
                                try {
                                    if (!Storage::exists($path)) {
                                        Storage::put($path, $storage->get($path));
                                        $count++;
                                        echo "【download】 $path ----------------- \n";
                                    } else {
                                        echo "【存在】$path ----------------- \n";
                                    }
                                } catch (\Exception $exception) {
                                }
                            }
                        }
                    }
                });
            });
        echo "end count = $count-------------- \n";
    }

    protected function move()
    {
        $this->moveQueryChunkFile(PatentApply::class, ['file', 'cert', 'retrieval_report']);
        echo "【PatentApply】end-----------------------\n ";
        $this->moveQueryChunkFile(BookApply::class, ['file', 'cert']);
        echo "【BookApply】end-----------------------\n ";
        $this->moveQueryChunkFile(PlantVariety::class, ['cert']);
        echo "【PlantVariety】end-----------------------\n ";
        $this->moveQueryChunkFile(Transverse::class, ['file', 'file2']);
        echo "【Transverse】end-----------------------\n ";
        $this->moveQueryChunkFile(PatentAssess::class, ['path']);
        echo "【PatentAssess】end-----------------------\n ";
        $this->moveQueryChunkFile(Document::class, ['path']);
        echo "【Document】end-----------------------\n ";
    }

    protected function moveQueryChunkFile($class, $fields)
    {
        $disk = config('admin.upload.disk');
        $class::orderBy('id')
            ->chunk(100, function ($list) use ($fields, $disk) {
                $list->map(function ($model) use ($fields, $disk) {
                    $this->moveModelFiles($model, $fields, $disk);
                });
            });
    }


    protected function moveModelFiles(Model $model, $fields, $disk)
    {
        foreach ($fields as $field) {
            if ($path = $model->$field) {
                $storage = Storage::disk($disk);
                $basePath = path_info($path, PATHINFO_DIRNAME);
                if (!strstr($basePath, '/') || $basePath === 'book/apply') {
                    if ($model instanceof Document) {
                        $newPath = 'uploads/files/' . basename($path);
                    } else {
                        $newPath = 'files/' . date('Ym', strtotime($model['created_at'])) . '/' . basename($path);
                    }
                    if (!$storage->exists($newPath) && $storage->exists($path)) {
                        try {
                            $storage->put($newPath, $storage->get($path));
                            if ($storage->exists($newPath)) {
                                $model->$field = $newPath;
                                $model->save();
                                $storage->delete($path);
                                echo "【move】$newPath -------------- \n";
                            }
                        } catch (\Exception $exception) {
                        }
                    }
                }
            }
        }
    }

}
